#include <stdio.h>
#include <string>

// linux
#include <unistd.h>
#include <sys/wait.h>
#include <sys/stat.h>

#include "cJSON.h"
#include "args.hpp"
#include "utils/autofile.hpp"

using std::shared_ptr;
using std::string;

void check_repos(string path) {
	if (!access(path.c_str(), F_OK)) {
		mkdir(path.c_str(), 0755);
	}
}

void git_clone(string prefix, string repo_name) {
	const char *git = "/usr/bin/git";
	string clone_addr = prefix + repo_name;
	string repo_path = get_parser()->get<string>("repo_dir") + string("/") + repo_name;

	check_repos(get_parser()->get<string>("repo_dir"));

	int pid = vfork();
	if (pid < 0) {
		printf("vfork failed\n");
	} else if (pid > 0) {
		// parent
		int ret_stat;
		waitpid(pid, &ret_stat, 0);
		perror("ret_stat");
		printf("ret_stat: %d\n", ret_stat);
	} else {
		// child
		execl(git, git, "clone", clone_addr.c_str(), repo_path.c_str(), NULL);
	}
}

int main(int argc, char **argv)
{
	init_parser(argc, argv);
	shared_ptr<autofile> file;

	file = autofile::read_file(get_parser()->get<string>("manifest"));
	if (!file->is_open()) {
		return ENOENT;
	}

	cJSON *root = cJSON_Parse(file->get_str());
	cJSON *clone_prefix = cJSON_GetObjectItem(root, "clone_prefix");
	cJSON *projects = cJSON_GetObjectItem(root, "projects");
	if (cJSON_IsArray(projects)) {
		cJSON *project;
		cJSON_ArrayForEach(project, projects) {
			cJSON *project_address = cJSON_GetObjectItem(project, "address");
			git_clone(clone_prefix->valuestring, project_address->valuestring);
		}
	}
	return 0;
}
